package com.software.loginregister.activity;

import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.software.loginregister.R;


import com.software.loginregister.adapter.MyWorksAdapter;
import com.software.loginregister.api.WorksApi;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.Works;
import com.software.loginregister.entity.room.WorksRoom;
import com.software.loginregister.entity.vo.CookingStepVO;
import com.software.loginregister.entity.vo.IngredientDTO;
import com.software.loginregister.entity.vo.MyWorkDetailVO;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;


import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import com.software.loginregister.databasesHelper.WorksDao;
import com.software.loginregister.databasesHelper.AppDatabase;

public class WorksActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private MyWorksAdapter adapter;
    private ImageButton backButton;
    private TextView titleTextView;
    private AppDatabase db;
    private WorksDao worksDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_works);

        // 初始化数据库
        db = AppDatabase.getDatabase(this);
        worksDao = db.worksDao();

        // 初始化视图
        initViews();
        // 设置返回按钮点击事件
        backButton.setOnClickListener(v -> finish());
        // 设置标题
        titleTextView.setText("我的作品");
        
        // 获取用户作品数据
        loadUserWorks();
    }

    private void initViews() {
        recyclerView = findViewById(R.id.recyclerView);
        backButton = findViewById(R.id.backButton);
        titleTextView = findViewById(R.id.titleTextView);
        
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MyWorksAdapter();
        recyclerView.setAdapter(adapter);
    }

    private void loadUserWorks() {
        Long userId = SharedPreferencesUtil.getUserId(this);
        if (userId == null) {
            Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 先从本地数据库加载
        new Thread(() -> {
            List<WorksRoom> localWorks = worksDao.getAllWorks();
            runOnUiThread(() -> {
                if (!localWorks.isEmpty()) {
                    List<MyWorkDetailVO> works = convertToWorksList(localWorks);
                    adapter.setWorksList(works);
                }
            });
        }).start();

        // 从网络加载
        RetrofitClient.getInstance()
                .create(WorksApi.class)
                .getUserWorks(Math.toIntExact(userId))
                .enqueue(new Callback<Result<List<MyWorkDetailVO>>>() {
                    @Override
                    public void onResponse(Call<Result<List<MyWorkDetailVO>>> call, 
                                        Response<Result<List<MyWorkDetailVO>>> response) {
                        if (response.isSuccessful() && response.body() != null 
                            && response.body().getData() != null) {
                            List<MyWorkDetailVO> works = response.body().getData();
                            adapter.setWorksList(works);
                            
                            // 保存到本地数据库
                            saveWorksToLocalDb(works);
                        } else {
                            Toast.makeText(WorksActivity.this, "获取数据失败", 
                                         Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<List<MyWorkDetailVO>>> call, Throwable t) {
                        Toast.makeText(WorksActivity.this, "网络请求失败: " + t.getMessage(), 
                                     Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void saveWorksToLocalDb(List<MyWorkDetailVO> works) {
        new Thread(() -> {
            // 清除旧数据
            try {
                worksDao.deleteAll();

                // 保存新数据
                for (MyWorkDetailVO work : works) {
                    WorksRoom worksRoom = new WorksRoom();
                    worksRoom.setWorksId(Long.parseLong(work.getWorkId()));
                    worksRoom.setWorksName(work.getTitle());
                    worksRoom.setDescription(work.getContentSummary());
                    worksRoom.setPhotoUrl(work.getImageUrl());

                    // 保存食材列表
                    StringBuilder ingredients = new StringBuilder();
                    if (work.getIngredients() != null) {
                        for (IngredientDTO ingredient : work.getIngredients()) {
                            ingredients.append(ingredient.getIngredientName())
                                    .append(": ")
                                    .append(ingredient.getAmount())
                                    .append("\n");
                        }
                    }
                    worksRoom.setIngredients(ingredients.toString());

                    // 保存烹饪步骤
                    StringBuilder steps = new StringBuilder();
                    if (work.getCookingSteps() != null) {
                        for (CookingStepVO step : work.getCookingSteps()) {
                            steps.append("步骤").append(step.getStepNumber())
                                    .append(": ").append(step.getDescription())
                                    .append("\n");
                        }
                    }
                    worksRoom.setCookingSteps(steps.toString());

                    // 保存用户信息和互动数据
                    worksRoom.setUserId(work.getUserId());
                    worksRoom.setNickname(work.getNickname());
                    worksRoom.setAvatarUrl(work.getAvatarUrl());
                    worksRoom.setLikeCount(work.getLikeCount());
                    worksRoom.setCommentCount(work.getCommentCount());

                    worksDao.insert(worksRoom);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

    }

    private List<MyWorkDetailVO> convertToWorksList(List<WorksRoom> worksRooms) {
        List<MyWorkDetailVO> worksList = new ArrayList<>();
        for (WorksRoom worksRoom : worksRooms) {
            MyWorkDetailVO work = new MyWorkDetailVO();
            work.setWorkId(String.valueOf(worksRoom.getWorksId()));
            work.setTitle(worksRoom.getWorksName());
            work.setContentSummary(worksRoom.getDescription());
            work.setImageUrl(worksRoom.getPhotoUrl());
            work.setUserId(worksRoom.getUserId());
            work.setNickname(worksRoom.getNickname());
            work.setAvatarUrl(worksRoom.getAvatarUrl());
            work.setLikeCount(worksRoom.getLikeCount());
            work.setCommentCount(worksRoom.getCommentCount());
            
            // TODO: 转换食材和步骤列表
            // 这里需要根据实际存储格式解析字符串为对象列表
            
            worksList.add(work);
        }
        return worksList;
    }
}
